package edu.ustb.railwayticket.service;

import edu.ustb.railwayticket.entity.Ticket;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TicketService {

    static String timePattern = "yyyy-MM-dd HH:mm:ss";
    static SimpleDateFormat sdf = new SimpleDateFormat(timePattern);
    Map<Integer, Ticket> passengerRecord = new HashMap<>();
    Map<Ticket, String> ticketRecord = new HashMap<>();
    Queue<Ticket> tickets = new LinkedList<>();
    Integer ticketNum = 1;
    Integer seatNum = 1;
    Integer trainNum = 1;
    Integer totalTicketNum = 120;

    /**
     * 订票服务
     * @param passengerNum
     */
    public Ticket order(Integer passengerNum, String departureTime, String departure, String destination) {
        Ticket ticket = null;
        if(ticketNum > totalTicketNum) return null;

        String dueTime = sdf.format(new Date());
        ticket = new Ticket(ticketNum, 100, trainNum, passengerNum, seatNum, departure, destination, dueTime, departureTime);
        passengerRecord.put(passengerNum, ticket);
        if(ticket == null) return null;
        return ticket;
    }

    public String refund(Integer passengerNum) {
        Ticket ticket = null;
        if(passengerRecord.containsKey(passengerNum)) {
            passengerRecord.remove(passengerNum);
            return "Refund Successfully!";
        }
        return "passenger have not issued ticket!";
    }

    public String changeTime(Integer passengerNum, String depaetureTime) {
        Ticket ticket = null;

        if(passengerRecord.containsKey(passengerNum)) {
            ticket = passengerRecord.get(passengerNum);
            ticket.setDepartureTime(depaetureTime);
            passengerRecord.put(passengerNum, ticket);
            return "change time successfully, change depaeture time to " + depaetureTime;
        }
        return "passenger don not issue ticket";
    }

    public Ticket queryTicket(Integer ticketNum) {
        Ticket ticket = null;
        Iterator<Map.Entry<Integer, Ticket>> iter = passengerRecord.entrySet().iterator();
        while (iter.hasNext()){
            ticket = iter.next().getValue();
            if(ticket.getTicketNumber().equals(ticketNum)){
                System.out.println(ticket);
                return ticket;
            }
        }
        return ticket;
    }

    public Ticket queryPassenger(Integer passengerNum) {
        Ticket ticket = null;
        Iterator<Map.Entry<Integer, Ticket>> iter = passengerRecord.entrySet().iterator();
        while (iter.hasNext()){
            ticket = iter.next().getValue();
            if(ticket.getPassengerNumber().equals(passengerNum)){
                System.out.println(ticket);
                return ticket;
            }
        }
        return ticket;
    }
}
